<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    pieData: {
      type: Array,
      default: null
    },
    className: {
      type: String,
      default: 'chart'
    },
    pieName: {
      type: String,
      default: '饼图'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null
    }
  },

  watch: {
    pieData: {
      deep: true,
      handler() {
        this.initChart()
      }
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      const pieData = this.pieData.filter(val => {
        return !!val.name
      })
      this.setOptions(this.pieName, pieData)
    },

    setOptions(pieName, pieData) {
      this.chart.setOption({
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: 'middle',
          right: '5',
          itemWidth: 12,
          itemHeight: 12,
          orient: 'vertical',
          formatter: function(name) {
            // 获取legend显示内容
            const data = pieData
            // const total = 0
            let tarValue = 0
            for (let i = 0, l = data.length; i < l; i++) {
              // total += data[i].value
              if (data[i].name === name) {
                tarValue = data[i].value
              }
            }
            // const p = (tarValue / total * 100).toFixed(2)
            // return name + ' ' + ' ' + p + '%'
            return name + ' ' + tarValue
          }
        },
        tooltip: {
          backgroundColor: '#fff',
          confine: false
        },
        series: [
          {
            name: pieName,
            type: 'pie',
            center: ['25%', '50%'],
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: pieData
          }
        ]
      })
    }
  }
}
</script>
